package cn.smile.business.basic.impl;

import cn.smile.bean.dto.basic.BasicItemCountDTO;
import cn.smile.bean.dto.basic.BillBasicItemDTO;
import cn.smile.bean.dto.core.SysUserDTO;
import cn.smile.bean.entity.basic.BillBasicItem;
import cn.smile.bean.form.basic.bill.billBasicItemAddForm;
import cn.smile.bean.form.core.user.QueryUserForm;
import cn.smile.business.basic.IBillBasicItemService;
import cn.smile.business.core.ISysUserService;
import cn.smile.commons.constant.NumberConstant;
import cn.smile.commons.domain.BaseServiceImpl;
import cn.smile.repository.basic.BillBasicItemMapper;
import cn.smile.utils.BeanCopy;
import cn.smile.utils.DateFormatUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Slf4j
@Service
public class BillBasicItemServiceImpl extends BaseServiceImpl<BillBasicItemMapper, BillBasicItem> implements IBillBasicItemService {
    @Resource
    private ISysUserService userService;

    @Override
    public Boolean saveBillBasicItem(billBasicItemAddForm form) {
        log.info("[BillBasicItemServiceImpl].[saveBillBasicItem] ------> 保存消费账单基础项目 Start, form = {}", JSON.toJSONString(form));
        BillBasicItem entity = BeanCopy.copyBean(form, BillBasicItem.class);
        boolean flag = super.create(entity);
        log.info("[BillBasicItemServiceImpl].[saveBillBasicItem] ------> 保存消费账单基础项目 End, flag = {}", flag);
        return flag;
    }

    @Override
    public Map<String, List<BillBasicItemDTO>> getBasicByBillIds(List<String> billIds) {
        log.info("[BillBasicItemServiceImpl].[getBasicByBillIds] ------> 根据账单ID集合查询基础项目列表 Start");
        Map<String, List<BillBasicItemDTO>> dataMap = Maps.newHashMap();
        if (!CollectionUtils.isEmpty(billIds)) {
            LambdaQueryWrapper<BillBasicItem> qw = new QueryWrapper<BillBasicItem>().lambda().eq(BillBasicItem::getDeleted, Boolean.FALSE);
            qw.in(BillBasicItem::getBillId, billIds);
            List<BillBasicItem> basicList = baseMapper.selectList(qw);
            if (!CollectionUtils.isEmpty(basicList)) {
                Set<String> userIds = new HashSet<>(NumberConstant.EIGHT);
                basicList.forEach(entity -> userIds.add(entity.getOpeUserId()));
                QueryUserForm userForm = new QueryUserForm();
                userForm.setIds(Lists.newArrayList(userIds));
                Map<String, SysUserDTO> userMap = userService.getMyShopUserMap(userForm);
                for (BillBasicItem entity : basicList) {
                    BillBasicItemDTO dto = BeanCopy.copyBean(entity, BillBasicItemDTO.class);
                    if (!dataMap.containsKey(dto.getBillId())) {
                        dataMap.put(dto.getBillId(), Lists.newArrayList());
                    }
                    if (userMap.containsKey(entity.getOpeUserId())) {
                        dto.setOpeUserName(userMap.get(entity.getOpeUserId()).getNickName());
                        dto.setOpeUser(userMap.get(entity.getOpeUserId()));
                    }

                    dataMap.get(dto.getBillId()).add(dto);
                }
            }
        }

        log.info("[BillBasicItemServiceImpl].[getBasicByBillIds] ------> 根据账单ID集合查询基础项目列表 End");
        return dataMap;
    }

    @Override
    public Boolean delByBillId(String billId) {
        log.info("[BillBasicItemServiceImpl].[delByBillId] ------> 根据账单ID删除基础项目 Start, billId = {}", billId);
        List<BillBasicItem> basicList = baseMapper.selectList(new LambdaQueryWrapper<BillBasicItem>().eq(BillBasicItem::getDeleted, Boolean.FALSE).eq(BillBasicItem::getBillId, billId));
        int updateNum = NumberConstant.ZERO;
        if (!CollectionUtils.isEmpty(basicList)) {
            for (BillBasicItem entity : basicList) {
                super.delBaseCol(entity);
                updateNum += baseMapper.updateById(entity);
            }
        }
        log.info("[BillBasicItemServiceImpl].[delByBillId] ------> 根据账单ID删除基础项目 End, updateNum = {}", updateNum);
        return Boolean.TRUE;
    }

    @Override
    public Map<String, List<BasicItemCountDTO>> countItemByUser(List<String> userIds, String countMonth) {
        log.info("[BillBasicItemServiceImpl].[countItemByUser] 根据店员ID集合统计基础项目完成数量 Start");
        Map<String, List<BasicItemCountDTO>> dataMap = Maps.newHashMap();
        LambdaQueryWrapper<BillBasicItem> qw = new QueryWrapper<BillBasicItem>().lambda().eq(BillBasicItem::getDeleted, Boolean.FALSE);
        qw.in(BillBasicItem::getOpeUserId, userIds);
        String queryTimeStart = String.format("%s-01 00:00:00", countMonth);
        Date startDay = DateFormatUtil.parseStrToDate(queryTimeStart, DateFormatUtil.DATE_TIME_FORMAT_1);
        String queryTimeEnd = DateFormatUtil.parseDateToStr(DateFormatUtil.getLastDayOfMonth(startDay), DateFormatUtil.TO_DATE_END);
        qw.ge(BillBasicItem::getCreateTime, queryTimeStart);
        qw.le(BillBasicItem::getCreateTime, queryTimeEnd);
        List<BillBasicItem> basicItems = baseMapper.selectList(qw);
        Map<String, List<BillBasicItem>> userItemMap = Maps.newHashMap();
        if (!CollectionUtils.isEmpty(basicItems)) {
            for (BillBasicItem basicItem : basicItems) {
                if (!userItemMap.containsKey(basicItem.getOpeUserId())) {
                    userItemMap.put(basicItem.getOpeUserId(), Lists.newArrayList());
                }
                userItemMap.get(basicItem.getOpeUserId()).add(basicItem);
            }
        }
        if (!CollectionUtils.isEmpty(userItemMap)) {
            for (String userId : userItemMap.keySet()) {
                Map<String, BasicItemCountDTO> basicMap = Maps.newHashMap();
                List<BillBasicItem> userItems = userItemMap.get(userId);
                for (BillBasicItem userItem : userItems) {
                    if (!basicMap.containsKey(userItem.getBasicId())) {
                        BasicItemCountDTO dto = new BasicItemCountDTO();
                        dto.setBasicId(userItem.getBasicId());
                        dto.setBaseName(userItem.getBasicName());
                        dto.setCountNum(NumberConstant.ZERO);
                        basicMap.put(userItem.getBasicId(), dto);
                    }
                    BasicItemCountDTO dto = basicMap.get(userItem.getBasicId());
                    dto.setCountNum(dto.getCountNum() + NumberConstant.ONE);
                }
                if (!CollectionUtils.isEmpty(basicMap)) {
                    dataMap.put(userId, Lists.newArrayList(basicMap.values()));
                }
            }
        }
        log.info("[BillBasicItemServiceImpl].[countItemByUser] 根据店员ID集合统计基础项目完成数量 End");
        return dataMap;
    }
}
